package edu.caltech.cs.techerlink;

import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@SuppressWarnings("serial")
public class StudentServlet extends HttpServlet {
	private static final Logger log = Logger
			.getLogger(StudentServlet.class.getName());

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		String name = req.getParameter("newName");
		if (name.length() >= 100) {
			name = name.substring(0, 100);
		}
		name = name.replaceAll("\\<.*?>", "");

		Objectify ofy = ObjectifyService.begin();

//		For now, isTA defaults to 0
		Student student = new Student(user, name, 0);
		ofy.put(student);
		if (student.getId() != null) {
			// id was autogenerated
			log.info("Student " + student.getId() + " successfully created.  " + user + " " + name);
		} else {
			log.info("Failed to create student " + user + " " + name);
		}

		resp.sendRedirect("/");
	}

}